package io.netty.example.study.server.codec.handler;


import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.example.study.common.Operation;
import io.netty.example.study.common.OperationResult;
import io.netty.example.study.common.RequestMessage;
import io.netty.example.study.common.ResponseMessage;

/**
 * 对InBound事件的处理
 * 为什么使用SimpleChannelInboundHandler
 * 可以自动释放ByteBuf  ReferenceCountUtil.release(msg);
 */
public class OrderServerProcessHandler extends SimpleChannelInboundHandler<RequestMessage> {

    /**
     *
     * @param channelHandlerContext
     * @param requestMessage
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RequestMessage requestMessage) throws Exception {
        // 模拟内存泄露且不回收
//        ByteBuf buffer = channelHandlerContext.alloc().buffer();
        Operation operation = requestMessage.getMessageBody();
        OperationResult execute = operation.execute();
        // 将返回结果发送回去
        ResponseMessage responseMessage = new ResponseMessage();
        responseMessage.setMessageHeader(requestMessage.getMessageHeader());
        responseMessage.setMessageBody(execute);
        // 保护程序不OOM
        if(channelHandlerContext.channel().isActive() && channelHandlerContext.channel().isWritable()){
            // 自己把他写出去
            channelHandlerContext.writeAndFlush(responseMessage);
        }else {
            System.out.println("信息丢失");
        }
    }
}
